package com.station.service.impl;

import com.google.gson.Gson;
import com.google.gson.internal.LinkedTreeMap;
import com.kingdee.bos.webapi.entity.RepoResult;
import com.station.entity.EnergystationBaseinfoEntity;
import com.station.entity.KingErpBillRecord;
import com.station.enums.ErpOrderTypeEnum;
import com.station.param.request.payBill.PayBillModel;
import com.station.param.request.purchase.InStock.InStockRequest;
import com.station.param.request.purchase.PurchaseOrderRequest;
import com.station.param.request.purchase.PurchaseReturnRequest;
import com.station.service.EnergystationBaseinfoService;
import com.station.service.KingErpBillRecordService;
import com.station.service.PurchaseDataService;
import com.station.service.mapper.AdvancePayMapper;
import com.station.service.mapper.ItemMapper;
import com.station.service.mapper.PurchaseMapper;
import com.station.service.mapper.UnitMapper;
import com.station.utils.DateUtils;
import com.station.utils.KingDeeUtils;
import com.station.utils.R;
import com.station.utils.StringUtils;
import com.station.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @Description:
 * @Author: dongfangyu
 * @Date: 2025/9/17
 */
@Slf4j
@Service
public class PurchaseDataServiceImpl implements PurchaseDataService {
    @Autowired
    private PurchaseMapper purchaseMapper;
    @Autowired
    private UnitMapper unitMapper;
    @Autowired
    private ItemMapper itemMapper;
    @Autowired
    private AdvancePayMapper advancePayMapper;
    @Autowired
    private EnergystationBaseinfoService energystationBaseinfoService;
    @Autowired
    private KingErpBillRecordService kingErpBillRecordService;

    @Value("${rd.bld.vendorId}")
    private String vendorId;
    @Value("${rd.kingdee.inStockType}")
    private String inStockType;
    @Value("${rd.kingdee.FCustId}")
    private String FCustId;
    @Value("${rd.kingdee.FSalerId}")
    private String FSalerId;
    @Value("${rd.kingdee.payBillType}")
    private String payBillType;
    @Value("${rd.kingdee.purchaseType}")
    private String purchaseType;
    @Value("${rd.kingdee.purchaseReturnType}")
    private String purchaseReturnType;
    /**
     * 分组前缀
     */
    private static final String F_GROUP_PREFIX = "03.13";
    /**
     * 供应商分组
     */
    private static final String F_SUPPLIER_GROUP_PREFIX = "08";
    /**
     * 销售入库单批量保存业务标识
     */
    private static final String FormId_InStock = "STK_InStock";
    /**
     * 货主类型
     */
    private static final String BD_OwnerOrg = "BD_OwnerOrg";
    /**
     * 创建组织
     */
    private static final String F_CREATE_ORG_ID = "100";
    /**
     * 采购订单批量保存业务标识
     */
    private static final String PUR_PurchaseOrder = "PUR_PurchaseOrder";
    /**
     * 采购退料单批量保存业务标识
     */
    private static final String PUR_MRB = "PUR_MRB";

    /**
     * 顾客业务标识
     */
    private static final String BD_Customer = "BD_Customer";
    /**
     * 往来单位
     */
    private static final String CUST0067 = "CUST0067";

    /**
     * 币别 人民币
     */
    private static final String PRE001 = "PRE001";
    /**
     * 现金结算
     */
    private static final String JSFS01_SYS = "JSFS01_SYS";
    /**
     * 预付款
     */
    private static final String SFKYT09_SYS = "SFKYT09_SYS";
    /**
     * 付款单单批量保存业务标识
     */
    private static final String AP_PAYBILL = "AP_PAYBILL";

    /**
     * 库存状态
     */
    private static final String KCZT01_SYS = "KCZT01_SYS";
    /**
     * 往来单位
     */
    private static final String BD_Supplier = "BD_Supplier";


    @Override
    public R batchSyncPurchase(String startDate, String endDate, List<AdvancePay> advancePays) {
        List<PurchOrder> purchOrders = new ArrayList<>();
        if(advancePays!= null && advancePays.size()>0){
            for (AdvancePay advancePay : advancePays) {
                PurchOrder purchOrder = purchaseMapper.queryOrderByOrderNo(Long.valueOf(vendorId), advancePay.getPurchaseOrdeNo(), 1);  //有预付的采购订单
                purchOrder.setAdvancePay(advancePay);
                purchOrders.add(purchOrder);
            }
        }else{
            if (StringUtils.isEmpty(startDate) || StringUtils.isEmpty(endDate)) {
                String[] perDate = DateUtils.getPerDate();
                startDate = perDate[0];
                endDate = perDate[1];
            }
            purchOrders  = purchaseMapper.queryOrderList(Long.valueOf(vendorId), startDate, endDate);
        }
        List<KingErpBillRecord> records = new ArrayList<>();

        if(purchOrders!=null && purchOrders.size()>0){
            for (PurchOrder purchOrder : purchOrders) {
                List<PurchDetail> purchDetails = purchaseMapper.queryOrderDetailList(purchOrder.getOrderNo());
                purchOrder.setDetailList(purchDetails);
            }
            if (!CollectionUtils.isEmpty(purchOrders)) {
                PurchaseOrderRequest.Model[] models = new PurchaseOrderRequest.Model[purchOrders.size()];
                int index = 0;
                for (PurchOrder purchOrder : purchOrders) {
                    List<PurchDetail> purchDetailList = purchOrder.getDetailList();
                    PurchaseOrderRequest.FPOOrderEntry[] fpoOrderEntries = new PurchaseOrderRequest.FPOOrderEntry[purchDetailList.size()];
                    int detailIndex = 0;
                    for (PurchDetail purchDetail : purchDetailList) {
                        //拼接明细数据
                        UnitVo unitVo = unitMapper.queryUnitByCondition(Long.valueOf(vendorId), purchDetail.getPurchUnit());
                        String unitCode = "Pcs";
                        if (null != unitVo && null != unitVo.getUnitCode()) {
                            unitCode = unitVo.getUnitCode();
                        }
                        PurchaseOrderRequest.FPOOrderEntry fpoOrderEntry = new PurchaseOrderRequest.FPOOrderEntry();
                        ItemVo itemVo = itemMapper.queryItemBySkuCode(Long.valueOf(vendorId), purchDetail.getSkuCode());
                        String cartId = null;
                        if (StringUtils.isEmpty(itemVo.getParentCode())) {
                            cartId = itemVo.getCatCode();
                        } else {
                            cartId = itemVo.getParentCode() + "." + itemVo.getCatCode();
                        }
                        fpoOrderEntry.setFMaterialId(new PurchaseOrderRequest.FMaterialId(F_GROUP_PREFIX + "." + cartId + "." + itemVo.getItemId()));
                        fpoOrderEntry.setFUnitId(new PurchaseOrderRequest.FUnitId(unitCode));
                        fpoOrderEntry.setFPriceUnitId(new PurchaseOrderRequest.FPriceUnitId(unitCode));
                        fpoOrderEntry.setFEntrySettleOrgId(new PurchaseOrderRequest.FEntrySettleOrgId(F_CREATE_ORG_ID));
                        fpoOrderEntry.setFStockUnitID(new PurchaseOrderRequest.FStockUnitID(unitCode));
                        fpoOrderEntry.setFQty(purchDetail.getQuantity());
                        fpoOrderEntry.setFPriceUnitQty(purchDetail.getQuantity());
                        fpoOrderEntry.setFStockQty(purchDetail.getQuantity());
                        fpoOrderEntry.setFPrice(purchDetail.getPurchPrice());  //单价
                        fpoOrderEntry.setFTaxPrice(purchDetail.getPurchPrice()); //含税单价
                        fpoOrderEntry.setFEntryTaxRate(Double.valueOf(0)); //税率
                        fpoOrderEntries[detailIndex++] = fpoOrderEntry;
                    }

                    //拼接订单数据
                    PurchaseOrderRequest.Model model = new PurchaseOrderRequest.Model();
                    model.setFBillTypeID(new PurchaseOrderRequest.FBillTypeID(purchaseType));
                    model.setFBillNo(purchOrder.getOrderNo());
                    model.setFBusinessType("2");
                    model.setFDate(purchOrder.getReviewTime());
                    model.setFSupplierId(new PurchaseOrderRequest.FSupplierId(purchOrder.getSupplierCode()));
                    model.setFPurchaseOrgId(new PurchaseOrderRequest.FPurchaseOrgId(F_CREATE_ORG_ID));
                    model.setFPOOrderEntry(fpoOrderEntries);
                    //如果这个采购订单是预付订单，则把这个预付金额传到erp
                    if(purchOrder.getAdvancePay()!= null){
                        PurchaseOrderRequest.FIinstallment[] fIinstallments = new PurchaseOrderRequest.FIinstallment[1];
                        PurchaseOrderRequest.FIinstallment fIinstallment = new PurchaseOrderRequest.FIinstallment();
                        fIinstallment.setFISPREPAYMENT(true);
                        fIinstallment.setFYFAMOUNT(purchOrder.getAdvancePay().getAdvancePayAmount());
                        fIinstallments[0] = fIinstallment;
                        model.setFIinstallment(fIinstallments);
                    }
                    models[index++] = model;

                    KingErpBillRecord billRecord = KingErpBillRecord.builder().
                            billDate(purchOrder.getReviewTime()).billType(ErpOrderTypeEnum.ERP_ORDER_TYPE_0.getValue().toString())
                            .orderNo(purchOrder.getOrderNo()).createTime(new Date()).stationId(Long.valueOf(purchOrder.getStoreCode())).isDel(0).build();
                    records.add(billRecord);
                }
                //同步采购收货单订单数据到金蝶
                PurchaseOrderRequest purchaseOrderRequest = new PurchaseOrderRequest();
                purchaseOrderRequest.setModel(models);
                purchaseOrderRequest.setIsAutoSubmitAndAudit(true);
                Gson requestGson = new Gson();
                String requestJson = requestGson.toJson(purchaseOrderRequest);
                RepoResult repoResult = KingDeeUtils.batchSave(PUR_PurchaseOrder, requestJson);

                if (repoResult.getResponseStatus().isIsSuccess()) {
                    for (KingErpBillRecord record : records) {
                        record.setStatus(1);
                        record.setUpdateTime(new Date());
                        kingErpBillRecordService.save(record);
                    }
                    return R.ok().put("data", repoResult.getResult());
                } else {
                    String msg = KingDeeUtils.toErrorMessageString(repoResult.getResponseStatus().getErrors());
                    for (KingErpBillRecord record : records) {
                        record.setStatus(0);
                        record.setResponText(msg);
                        record.setUpdateTime(new Date());
                        kingErpBillRecordService.save(record);
                    }
                    return R.error(msg);
                }
            }else{
                return R.error("未查询到采购订单数据！");
            }
        } else{
            return R.error("未查询到采购订单数据！");
        }

    }

    @Override
    public R batchSyncInStock(String startDate, String endDate) {
        if (StringUtils.isEmpty(startDate) || StringUtils.isEmpty(endDate)) {
            String[] perDate = DateUtils.getPerDate();
            startDate = perDate[0];
            endDate = perDate[1];
        }
        List<PurchOrder> purchOrders = purchaseMapper.queryInStockOrderList(Long.valueOf(vendorId), startDate, endDate);
        for (PurchOrder purchOrder : purchOrders) {
            List<PurchDetail> purchDetails = purchaseMapper.queryOrderDetailList(purchOrder.getOrderNo());
            purchOrder.setDetailList(purchDetails);
        }
        if (!CollectionUtils.isEmpty(purchOrders)) {
            InStockRequest.InStockModel[] models = new InStockRequest.InStockModel[purchOrders.size()];
            int index = 0;
            List<KingErpBillRecord> records = new ArrayList<>();
            for (PurchOrder purchOrder : purchOrders) {
                List<PurchDetail> purchDetailList = purchOrder.getDetailList();
                InStockRequest.FInStockEntry[] fInStockEntries = new InStockRequest.FInStockEntry[purchDetailList.size()];
                int detailIndex = 0;
                for (PurchDetail purchDetail : purchDetailList) {
                    //拼接明细数据
                    UnitVo unitVo = unitMapper.queryUnitByCondition(Long.valueOf(vendorId), purchDetail.getPurchUnit());
                    String unitCode = "Pcs";
                    if (null != unitVo && null != unitVo.getUnitCode()) {
                        unitCode = unitVo.getUnitCode();
                    }
                    InStockRequest.FInStockEntry fInStockEntry = new InStockRequest.FInStockEntry();
                    ItemVo itemVo = itemMapper.queryItemBySkuCode(Long.valueOf(vendorId), purchDetail.getSkuCode());
                    String cartId = null;
                    if (StringUtils.isEmpty(itemVo.getParentCode())) {
                        cartId = itemVo.getCatCode();
                    } else {
                        cartId = itemVo.getParentCode() + "." + itemVo.getCatCode();
                    }
                    fInStockEntry.setFMaterialId(new InStockRequest.FNumberObject(F_GROUP_PREFIX + "." + cartId + "." + itemVo.getItemId()));
                    fInStockEntry.setFUnitID(new InStockRequest.FNumberObject(unitCode));
                    fInStockEntry.setFPriceUnitID(new InStockRequest.FNumberObject(unitCode));
                    fInStockEntry.setFRemainInStockUnitId(new InStockRequest.FNumberObject(unitCode));
                    fInStockEntry.setFOWNERTYPEID("BD_OwnerOrg"); //
                    fInStockEntry.setFOWNERID(new InStockRequest.FNumberObject("100")); //
                    fInStockEntry.setFStockId(new InStockRequest.FNumberObject("bld"+ purchOrder.getStoreCode()));
                    fInStockEntry.setFReceiveStockID(new InStockRequest.FNumberObject("bld"+purchOrder.getStoreCode()));
                    fInStockEntry.setFRealQty(purchDetail.getQuantity());      //实收数量
                    fInStockEntry.setFPriceUnitQty(purchDetail.getQuantity());  //计价数量
                    fInStockEntry.setFSRCBillNo(purchOrder.getRefOrderNo()); //源单单号
                    fInStockEntry.setFSRCBILLTYPEID(PUR_PurchaseOrder);  //源单类型
                    fInStockEntries[detailIndex++] = fInStockEntry;
                }
                EnergystationBaseinfoVo vo = new EnergystationBaseinfoVo();
                vo.setEnergystationid(Long.valueOf(purchOrder.getStoreCode()));
                EnergystationBaseinfoEntity entity = energystationBaseinfoService.query(vo);
                //拼接订单数据
                InStockRequest.InStockModel model = new InStockRequest.InStockModel();
                model.setFBillTypeID(new InStockRequest.FBillTypeID(inStockType));
                model.setFBillNo(purchOrder.getOrderNo());
                model.setFBusinessType("2");
                model.setFDate(purchOrder.getReviewTime());
                model.setFStockOrgId(new InStockRequest.FNumberObject(F_CREATE_ORG_ID));
                model.setFPurchaseOrgId(new InStockRequest.FNumberObject(F_CREATE_ORG_ID));
                model.setFPurchaseDeptId(new InStockRequest.FNumberObject(entity.getDeptNumber()));
                model.setFSupplierId(new InStockRequest.FNumberObject(purchOrder.getSupplierCode()));
                model.setFOwnerTypeIdHead(BD_OwnerOrg);  //货主类型
                model.setFOwnerIdHead(new InStockRequest.FNumberObject(F_CREATE_ORG_ID)); //货主
                model.setFInStockEntry(fInStockEntries);
                models[index++] = model;

                KingErpBillRecord billRecord = KingErpBillRecord.builder().
                        billDate(purchOrder.getReviewTime()).billType(ErpOrderTypeEnum.ERP_ORDER_TYPE_1.getValue().toString())
                        .orderNo(purchOrder.getOrderNo()).createTime(new Date()).stationId(Long.valueOf(purchOrder.getStoreCode())).isDel(0).build();
                records.add(billRecord);
            }
            //同步采购收货单订单数据到金蝶
            InStockRequest inStockRequest = new InStockRequest();
            inStockRequest.setModel(models);
            Gson requestGson = new Gson();
            String requestJson = requestGson.toJson(inStockRequest);
            RepoResult repoResult = KingDeeUtils.batchSave(FormId_InStock, requestJson);
            if (repoResult.getResponseStatus().isIsSuccess()) {
                for (KingErpBillRecord record : records) {
                    record.setStatus(1);
                    record.setUpdateTime(new Date());
                    kingErpBillRecordService.save(record);
                }
                return R.ok().put("data", repoResult.getResult());
            } else {
                String msg = KingDeeUtils.toErrorMessageString(repoResult.getResponseStatus().getErrors());
                for (KingErpBillRecord record : records) {
                    record.setStatus(0);
                    record.setResponText(msg);
                    record.setUpdateTime(new Date());
                    kingErpBillRecordService.save(record);
                }
                return R.error(msg);
            }
        }
        return R.ok("未查询到采购收货单订单数据！");
    }

    @Override
    public R batchSyncPayBill(String startDate, String endDate) {
        if (StringUtils.isEmpty(startDate) || StringUtils.isEmpty(endDate)) {
            String[] perDate = DateUtils.getPerDate();
            startDate = perDate[0];
            endDate = perDate[1];
        }
        List<AdvancePay> advancePays = advancePayMapper.queryOrderList(Long.valueOf(vendorId), startDate, endDate);
        for (AdvancePay advancePay : advancePays) {
            List<AdvancePayDetail> advancePayDetails = advancePayMapper.queryOrderDetailList(advancePay.getOrderNo());
            advancePay.setAdvancePayDetailList(advancePayDetails);
        }
        if (!CollectionUtils.isEmpty(advancePays)) {
            PayBillModel.ModelDTO[] models = new PayBillModel.ModelDTO[advancePays.size()];
            int index = 0;
            List<KingErpBillRecord> records = new ArrayList<>();
            for (AdvancePay advancePay : advancePays) {
                List<AdvancePayDetail> advancePayDetails = advancePay.getAdvancePayDetailList();
                PayBillModel.PayBillEntryDTO[] payBillEntryDTOS = new PayBillModel.PayBillEntryDTO[advancePayDetails.size()];
                int detailIndex = 0;
                for (AdvancePayDetail advancePayDetail : advancePayDetails) {
                    PayBillModel.PayBillEntryDTO payBillEntryDTO = new PayBillModel.PayBillEntryDTO();
                    payBillEntryDTO.setFPAYITEMTYPE("2");  //预付项目类型 2采购订单  1供应商
                    payBillEntryDTO.setFSettleTypeId(new PayBillModel.SettleTypeIdDTO(JSFS01_SYS)); //结算方式 现金结算
                    payBillEntryDTO.setFPURPOSEID(new PayBillModel.PurposeIdDTO(SFKYT09_SYS)); // 付款用途 预付款
                    payBillEntryDTO.setFPostDate(DateUtils.format(advancePay.getOrderDate()));
                    payBillEntryDTO.setFPAYTOTALAMOUNTFOR(advancePayDetail.getAmount()); //应付金额
                    payBillEntryDTO.setFPAYAMOUNTFOR_E(advancePayDetail.getAmount()); //付款金额
                    //payBillEntryDTO.setFPAYAMOUNT_E(advancePayDetail.getAmount());//应付金额
                    payBillEntryDTO.setFPayItem(advancePay.getPurchaseOrdeNo());  //采购订单
                    payBillEntryDTO.setFEntryPrepayOrderNo(advancePay.getPurchaseOrdeNo()); //采购订单
                    R purchaseOrderByNo = this.getPurchaseOrderByNo(advancePay.getPurchaseOrdeNo());
                    String code = (String) purchaseOrderByNo.get("code");
                    if("success".equals(code)){
                        String msg = (String) purchaseOrderByNo.get("msg");
                        payBillEntryDTO.setFPURCHASEORDERID(Double.valueOf(msg));
                    }
                    payBillEntryDTOS[detailIndex++] = payBillEntryDTO;
                }
                //拼接订单数据
                PayBillModel.ModelDTO model = new PayBillModel.ModelDTO();
                model.setFBillTypeID(new PayBillModel.BillTypeIdDTO(payBillType));
                model.setFBillNo(advancePay.getOrderNo());
                model.setFPayOrgId(new PayBillModel.OrgIdDTO(F_CREATE_ORG_ID));
                model.setFDate(advancePay.getCreateDate());
                model.setFContactUnitType(BD_Supplier); //往来单位类型
                model.setFPAYUNITTYPE(BD_Supplier);  // 付款单位类型
                model.setFContactUnit(new PayBillModel.ContactUnitDTO(advancePay.getRelatedCode()));   //往来单位 供应商
                model.setFPAYUNIT(new PayBillModel.NumberEntity(advancePay.getRelatedCode())); //付款单位 供应商
                model.setFCurrencyId(new PayBillModel.CurrencyIdDTO(PRE001)); //币别
                model.setFSettleCur(new PayBillModel.SettleCurDTO(PRE001)); //结算币别
                model.setFDocumentStatus("A"); //单据状态 单据状态A创建B审核中C已审核D 重新审核
                //model.setFBusinessType("1"); // 业务类型
                model.setFCancelStatus("A");  //作废 A 否 B 是
                model.setFSettleMainBookId(new PayBillModel.MainBookIdDTO(PRE001)); //结算本位币
                //model.setFPAYAMOUNTFOR(advancePay.getAdvancePayAmount()); //应付金额
                model.setFPAYBILLENTRY(payBillEntryDTOS);
                models[index++] = model;

                KingErpBillRecord billRecord = KingErpBillRecord.builder().
                        billDate(advancePay.getApproveDate()).billType(ErpOrderTypeEnum.ERP_ORDER_TYPE_2.getValue().toString())
                        .orderNo(advancePay.getOrderNo()).createTime(new Date()).stationId(Long.valueOf(advancePay.getStoreCode())).isDel(0).build();
                records.add(billRecord);
            }
            //同步采购收货单订单数据到金蝶
            PayBillModel payBillModel = new PayBillModel();
            payBillModel.setModel(models);
            Gson requestGson = new Gson();
            String requestJson = requestGson.toJson(payBillModel);
            RepoResult repoResult = KingDeeUtils.batchSave(AP_PAYBILL, requestJson);
            if (repoResult.getResponseStatus().isIsSuccess()) {
                for (KingErpBillRecord record : records) {
                    record.setStatus(1);
                    record.setUpdateTime(new Date());
                    kingErpBillRecordService.save(record);
                }
                return R.ok().put("data", repoResult.getResult());
            } else {
                String msg = KingDeeUtils.toErrorMessageString(repoResult.getResponseStatus().getErrors());
                for (KingErpBillRecord record : records) {
                    record.setStatus(0);
                    record.setResponText(msg);
                    record.setUpdateTime(new Date());
                    kingErpBillRecordService.save(record);
                }
                return R.error(msg);
            }
        }
        return R.ok("未查询到采购付款单订单数据！");
    }
    /**
     * 确定需要同步的有预付款的采购数据
     **/
    @Override
    public R payBillByPurchase(String startDate, String endDate) {
        if (StringUtils.isEmpty(startDate) || StringUtils.isEmpty(endDate)) {
            String[] perDate = DateUtils.getPerDate();
            startDate = perDate[0];
            endDate = perDate[1];
        }
        List<AdvancePay> advancePays = advancePayMapper.queryOrderList(Long.valueOf(vendorId), startDate, endDate);
        //查询到数据后，同步采购订单数据
        return this.batchSyncPurchase(null, null, advancePays);
    }



    @Override
    public R batchSyncPurchaseReturn(String startDate, String endDate) {
        if (StringUtils.isEmpty(startDate) || StringUtils.isEmpty(endDate)) {
            String[] perDate = DateUtils.getPerDate();
            startDate = perDate[0];
            endDate = perDate[1];
        }
        List<PurchOrder> purchOrders  = purchaseMapper.queryPurchaseReturnOrderList(Long.valueOf(vendorId), startDate, endDate);

        if(purchOrders!=null && purchOrders.size()>0){
            for (PurchOrder purchOrder : purchOrders) {
                List<PurchDetail> purchDetails = purchaseMapper.queryOrderDetailList(purchOrder.getOrderNo());
                purchOrder.setDetailList(purchDetails);
            }
            if (!CollectionUtils.isEmpty(purchOrders)) {
                PurchaseReturnRequest.Model[] models = new PurchaseReturnRequest.Model[purchOrders.size()];
                int index = 0;
                List<KingErpBillRecord> records = new ArrayList<>();
                for (PurchOrder purchOrder : purchOrders) {
                    List<PurchDetail> purchDetailList = purchOrder.getDetailList();
                    PurchaseReturnRequest.FPURMRBENTRY[] entries = new PurchaseReturnRequest.FPURMRBENTRY[purchDetailList.size()];
                    int detailIndex = 0;
                    for (PurchDetail purchDetail : purchDetailList) {
                        //拼接明细数据
                        UnitVo unitVo = unitMapper.queryUnitByCondition(Long.valueOf(vendorId), purchDetail.getPurchUnit());
                        String unitCode = "Pcs";
                        if (null != unitVo && null != unitVo.getUnitCode()) {
                            unitCode = unitVo.getUnitCode();
                        }
                        PurchaseReturnRequest.FPURMRBENTRY entity = new PurchaseReturnRequest.FPURMRBENTRY();
                        ItemVo itemVo = itemMapper.queryItemBySkuCode(Long.valueOf(vendorId), purchDetail.getSkuCode());
                        String cartId = null;
                        if (StringUtils.isEmpty(itemVo.getParentCode())) {
                            cartId = itemVo.getCatCode();
                        } else {
                            cartId = itemVo.getParentCode() + "." + itemVo.getCatCode();
                        }
                        entity.setFMATERIALID(new PurchaseReturnRequest.FNumberObj(F_GROUP_PREFIX + "." + cartId + "." + itemVo.getItemId())); //物料编码
                        entity.setFUnitID(new PurchaseReturnRequest.FNumberObj(unitCode));  //库存单位
                        entity.setFMaterialDesc(purchDetail.getSkuName());  //物料说明
                        entity.setFRMREALQTY(purchDetail.getQuantity());  //实退数量
                        entity.setFREPLENISHQTY(purchDetail.getQuantity()); //补料数量
                        entity.setFKEAPAMTQTY(purchDetail.getQuantity()); //扣款数量
                        entity.setFPRICEUNITID(new PurchaseReturnRequest.FNumberObj(unitCode)); //计价单位
                        entity.setFSTOCKID(new PurchaseReturnRequest.FNumberObj("bld"+purchOrder.getStoreCode()));  //仓库
                        entity.setFStockStatusId(new PurchaseReturnRequest.FNumberObj(KCZT01_SYS)); //库存状态
                        entity.setFPriceBaseQty(purchDetail.getQuantity());  //计价基本数量
                        //entity.setFCarryUnitId(new PurchaseReturnRequest.FNumberObj(unitCode));  //采购单位
                        //entity.setFCarryQty(purchDetail.getQuantity());  //采购数量
                        //entity.setFCarryBaseQty(purchDetail.getQuantity());  //采购基本数量
                        entity.setFOWNERTYPEID(BD_OwnerOrg);  //货主类型
                        entity.setFOWNERID(new PurchaseReturnRequest.FNumberObj(F_CREATE_ORG_ID)); //货主
                        entity.setFPrice(purchDetail.getPurchPrice());  //单价
                        entries[detailIndex++] = entity;
                    }
                    PurchaseReturnRequest.FPURMRBFIN    fpurmrbfin = new PurchaseReturnRequest.FPURMRBFIN();
                    fpurmrbfin.setFSettleOrgId(new PurchaseReturnRequest.FNumberObj(F_CREATE_ORG_ID)); //结算组织
                    fpurmrbfin.setFSettleCurrId(new PurchaseReturnRequest.FNumberObj(PRE001));   //结算币别
                    fpurmrbfin.setFLOCALCURRID(new PurchaseReturnRequest.FNumberObj(PRE001)); //本位币
                    fpurmrbfin.setFPRICETIMEPOINT("1");  //定价时点
                    //拼接订单数据
                    PurchaseReturnRequest.Model model = new PurchaseReturnRequest.Model();
                    model.setFBillTypeID(new PurchaseReturnRequest.FNumberObj(purchaseReturnType));
                    model.setFBillNo(purchOrder.getOrderNo());
                    model.setFBusinessType("CG");
                    model.setFDate(purchOrder.getReviewTime());
                    model.setFMRTYPE("B");  //退料类型
                    model.setFMRMODE("A");   //退料方式
                    model.setFStockOrgId(new PurchaseReturnRequest.FNumberObj(F_CREATE_ORG_ID));  //退料组织
                    model.setFCorrespondOrgId(new PurchaseReturnRequest.FNumberObj(F_CREATE_ORG_ID));  //对应组织
                    model.setFRequireOrgId(new PurchaseReturnRequest.FNumberObj(F_CREATE_ORG_ID)); //需求组织
                    model.setFPurchaseOrgId(new PurchaseReturnRequest.FNumberObj(F_CREATE_ORG_ID)); //采购组织
                    //model.setFACCEPTORID(new PurchaseReturnRequest.FNumberObj(purchOrder.getSupplierCode())); //接收方
                    //model.setFSettleId(new PurchaseReturnRequest.FNumberObj(purchOrder.getSupplierCode()));  //结算方
                    model.setFOwnerTypeIdHead(BD_OwnerOrg);  //货主类型
                    model.setFOwnerIdHead(new PurchaseReturnRequest.FNumberObj(F_CREATE_ORG_ID)); //货主
                    model.setFPURMRBENTRY(entries);
                    model.setFSupplierID(new PurchaseReturnRequest.FNumberObj(purchOrder.getSupplierCode()));
                    model.setFPURMRBFIN(fpurmrbfin);
                    models[index++] = model;

                    KingErpBillRecord billRecord = KingErpBillRecord.builder().
                            billDate(purchOrder.getReviewTime()).billType(ErpOrderTypeEnum.ERP_ORDER_TYPE_3.getValue().toString())
                            .orderNo(purchOrder.getOrderNo()).createTime(new Date()).stationId(Long.valueOf(purchOrder.getStoreCode())).isDel(0).build();
                    records.add(billRecord);
                }
                //同步采购收货单订单数据到金蝶
                PurchaseReturnRequest purchaseReturnRequest = new PurchaseReturnRequest();
                purchaseReturnRequest.setModel(models);
                Gson requestGson = new Gson();
                String requestJson = requestGson.toJson(purchaseReturnRequest);
                RepoResult repoResult = KingDeeUtils.batchSave(PUR_MRB, requestJson);
                if (repoResult.getResponseStatus().isIsSuccess()) {
                    for (KingErpBillRecord record : records) {
                        record.setStatus(1);
                        record.setUpdateTime(new Date());
                        kingErpBillRecordService.save(record);
                    }
                    return R.ok().put("data", repoResult.getResult());
                } else {
                    String msg = KingDeeUtils.toErrorMessageString(repoResult.getResponseStatus().getErrors());
                    for (KingErpBillRecord record : records) {
                        record.setStatus(0);
                        record.setResponText(msg);
                        record.setUpdateTime(new Date());
                        kingErpBillRecordService.save(record);
                    }
                    return R.error(msg);
                }
            }else{
                return R.error("未查询到采购退货单订单数据！");
            }
        } else{
            return R.error("未查询到采购退货单订单数据！");
        }
    }

    @Override
    public R getPurchaseOrderByNo(String orderNo) {
        PurchaseOrderRequest.FSearchPurchase searchPurchase = new PurchaseOrderRequest.FSearchPurchase();
        searchPurchase.setNumber(orderNo);
        Gson requestGson = new Gson();
        String requestJson = requestGson.toJson(searchPurchase);
        RepoResult repoResult = KingDeeUtils.view(PUR_PurchaseOrder, requestJson);
        if (repoResult.getResponseStatus().isIsSuccess()) {
            //Object result = repoResult.getResult();
            LinkedTreeMap linkedTreeMap = (LinkedTreeMap) repoResult.getResult();
            Double id = (Double) linkedTreeMap.get("Id");
            return R.ok(id.toString());
        }else{
            return R.error("接口调用失败");
        }
    }



}
